Page({
    data: {
      car: null,
      loading: true,
      isFavorite: false,
      carId: null,
      
      // 租车弹窗相关数据
      showPopup: false,
      today: '',
      maxDate: '',
      pickupDate: '',
      pickupTime: '09:00',
      returnDate: '',
      returnTime: '09:00',
      rentalDays: 1,
      rentalTypes: [],
      selectedTypeId: null,
      selectedDiscount: 1,
      baseRentFee: 0,
      totalFee: 0
    },
    onLoad(options) {
      // 从URL参数中获取车辆ID
      const carId = options.id;
      if (!carId) {
        wx.showToast({
          title: '参数错误',
          icon: 'error'
        });
        this.setData({ loading: false });
        return;
      }
      
      this.setData({ carId });
      this.loadCarDetail(carId);
      
      // 初始化日期
      this.initDates();
    },
    
    // 初始化日期选择器的值
    initDates() {
      const today = new Date();
      const nextDay = new Date(today);
      nextDay.setDate(today.getDate() + 1);
      
      const maxDate = new Date(today);
      maxDate.setDate(today.getDate() + 60); // 最多可预订未来60天
      
      this.setData({
        today: this.formatDate(today),
        maxDate: this.formatDate(maxDate),
        pickupDate: this.formatDate(today),
        returnDate: this.formatDate(nextDay)
      });
      
      this.calculateRentalDays();
    },
    
    // 格式化日期为 YYYY-MM-DD
    formatDate(date) {
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      return `${year}-${month}-${day}`;
    },
    
    // 计算租期天数
    calculateRentalDays() {
      const pickup = new Date(`${this.data.pickupDate} ${this.data.pickupTime}`);
      const returnTime = new Date(`${this.data.returnDate} ${this.data.returnTime}`);
      
      // 计算相差的毫秒数，并转换为天数
      const diffTime = Math.abs(returnTime - pickup);
      const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
      
      // 至少租一天
      const rentalDays = Math.max(1, diffDays);
      
      const baseRentFee = this.data.car ? this.data.car.rent * rentalDays : 0;
      const totalFee = Math.round(baseRentFee * this.data.selectedDiscount);
      
      this.setData({
        rentalDays,
        baseRentFee,
        totalFee
      });
    },
    
    // 显示租车弹窗
    showRentPopup() {
      // 加载租车类型数据
      this.loadRentalTypes();
      
      // 计算基本费用
      this.calculateRentalDays();
      
      this.setData({
        showPopup: true
      });
    },
    
    // 关闭租车弹窗
    closeRentPopup() {
      this.setData({
        showPopup: false
      });
    },
    
    // 加载租车类型数据
    loadRentalTypes() {
      const app = getApp();
      const token = wx.getStorageSync('token');
      
      if (!token) {
        console.error('Token不存在，无法请求租车类型数据');
        return;
      }
      
      wx.request({
        url: `${app.globalData.baseUrl}/rental/rentalType/1/100`,
        method: 'POST',
        header: {
          'Content-Type': 'application/json',
          'token': token
        },
        data: {},
        success: (res) => {
          console.log('租车类型响应:', res.data);
          
          if (res.statusCode === 200 && res.data && res.data.code === 200 && res.data.data && res.data.data.records) {
            // 默认选择第一个租车类型
            const types = res.data.data.records;
            let selectedTypeId = null;
            let selectedDiscount = 1;
            
            if (types.length > 0) {
              selectedTypeId = types[0].id;
              selectedDiscount = types[0].typeDiscount;
            }
            
            this.setData({
              rentalTypes: types,
              selectedTypeId,
              selectedDiscount
            });
            
            // 重新计算价格
            this.calculateRentalDays();
          }
        },
        fail: (err) => {
          console.error('请求租车类型失败:', err);
          wx.showToast({
            title: '获取租车类型失败',
            icon: 'none'
          });
        }
      });
    },
    
    // 选择租车类型
    selectRentalType(e) {
      const typeId = e.currentTarget.dataset.id;
      const discount = e.currentTarget.dataset.discount;
      
      this.setData({
        selectedTypeId: typeId,
        selectedDiscount: discount
      });
      
      // 重新计算费用
      this.calculateRentalDays();
    },
    
    // 取车日期改变
    bindPickupDateChange(e) {
      // 确保取车日期不晚于还车日期
      const pickupDate = e.detail.value;
      const returnDate = this.data.returnDate;
      
      if (new Date(pickupDate) > new Date(returnDate)) {
        // 如果取车日期晚于还车日期，则更新还车日期
        this.setData({
          returnDate: pickupDate
        });
      }
      
      this.setData({
        pickupDate: pickupDate
      });
      
      this.calculateRentalDays();
    },
    
    // 取车时间改变
    bindPickupTimeChange(e) {
      this.setData({
        pickupTime: e.detail.value
      });
      
      this.calculateRentalDays();
    },
    
    // 还车日期改变
    bindReturnDateChange(e) {
      this.setData({
        returnDate: e.detail.value
      });
      
      this.calculateRentalDays();
    },
    
    // 还车时间改变
    bindReturnTimeChange(e) {
      this.setData({
        returnTime: e.detail.value
      });
      
      this.calculateRentalDays();
    },
    
    // 确认租车
    confirmRent() {
      const userId = wx.getStorageSync('userId'); // 从storage中获取用户ID
      const orderData = {
        autoId: this.data.car.id,
        customerId: userId, // 使用从storage中获取的用户ID
        rentalTime: `${this.data.pickupDate} ${this.data.pickupTime}`,
        returnTime: `${this.data.returnDate} ${this.data.returnTime}`,
        typeId: this.data.selectedTypeId,
        // 其他需要传递的数据
        image: this.data.car.pic,
        carName: `${this.data.car.makerName} ${this.data.car.brandName}`,
        carDesc: `${this.data.car.displacement}${this.data.car.unit} · ${this.data.car.mileage}公里`,
        price: this.data.car.rent,
        baseFee: this.data.baseRentFee,
        deposit: this.data.car.deposit,
        totalFee: this.data.totalFee
      };
      
      wx.navigateTo({
        url: `/pages/order-confirm/order-confirm?order=${encodeURIComponent(JSON.stringify(orderData))}`,
        success: () => {
          this.closeRentPopup();
        }
      });
    },
    
    loadCarDetail(carId) {
      this.setData({ loading: true });
      
      const app = getApp();
      const token = wx.getStorageSync('token');
      
      // 打印token以便调试
      console.log('当前使用的token:', token);
      console.log('正在查询的车辆ID:', carId);
      
      if (!token) {
        console.error('Token不存在，无法请求车辆数据');
        this.setData({ loading: false });
        wx.showToast({
          title: '请先登录',
          icon: 'none'
        });
        
        setTimeout(() => {
          wx.navigateTo({
            url: '/pages/login/login'
          });
        }, 1500);
        return;
      }
      
      // 发送请求获取特定ID的车辆详情
      // 修改查询方法，直接在URL中添加ID参数
      wx.request({
        // 使用正确的端点API根据ID获取车辆详情
        // 如果后端没有提供单个车辆查询API，则模拟一个
        url: `${app.globalData.baseUrl}/rental/autoInfo/detail/${carId}`, 
        method: 'GET',
        header: {
          'Content-Type': 'application/json',
          'token': token
        },
        success: (res) => {
          console.log('车辆详情响应:', res.data);
          
          // 尝试使用API返回的数据
          if (res.statusCode === 200 && res.data && res.data.code === 200 && res.data.data) {
            const carDetail = res.data.data;
            this.setData({
              car: carDetail,
              loading: false
            });
            
            // 设置导航栏标题
            wx.setNavigationBarTitle({
              title: `${carDetail.makerName} ${carDetail.brandName}`
            });
          } else {
            // 如果API不存在或返回错误，则尝试备用方法
            this.loadCarDetailBackup(carId);
          }
        },
        fail: (err) => {
          console.error('请求失败:', err);
          // 如果主方法失败，尝试备用方法
          this.loadCarDetailBackup(carId);
        }
      });
    },
    
    // 备用方法：使用分页API获取车辆详情
    loadCarDetailBackup(carId) {
      const app = getApp();
      const token = wx.getStorageSync('token');
      
      console.log('使用备用方法加载车辆详情, ID:', carId);
      
      // 使用车辆列表API，并循环查找指定ID
      wx.request({
        url: `${app.globalData.baseUrl}/rental/autoInfo/1/20`, // 获取更多条目以增加找到的可能性
        method: 'POST',
        header: {
          'Content-Type': 'application/json',
          'token': token
        },
        data: {}, // 不过滤，获取所有车辆
        success: (res) => {
          console.log('备用方法响应:', res.data);
          
          if (res.statusCode === 200 && res.data && res.data.code === 200 && 
              res.data.data && res.data.data.records) {
            
            // 从返回的列表中查找指定ID的车辆
            const carList = res.data.data.records;
            const targetCar = carList.find(car => car.id === parseInt(carId));
            
            if (targetCar) {
              this.setData({
                car: targetCar,
                loading: false
              });
              
              // 设置导航栏标题
              wx.setNavigationBarTitle({
                title: `${targetCar.makerName} ${targetCar.brandName}`
              });
            } else {
              this.setData({
                car: null,
                loading: false
              });
              
              wx.showToast({
                title: '未找到该车辆',
                icon: 'none'
              });
            }
          } else {
            this.setData({
              car: null,
              loading: false
            });
            
            console.error('获取车辆详情失败:', res.data);
            
            if (res.statusCode === 401 || res.statusCode === 403 || 
                (res.data && (res.data.code === 401 || res.data.code === 403))) {
              // 未授权，可能是token过期或无效
              wx.removeStorageSync('token');
              wx.showToast({
                title: '登录已过期，请重新登录',
                icon: 'none'
              });
              
              setTimeout(() => {
                wx.navigateTo({
                  url: '/pages/login/login'
                });
              }, 1500);
            } else {
              wx.showToast({
                title: res.data.message || '获取车辆信息失败',
                icon: 'none'
              });
            }
          }
        },
        fail: (err) => {
          console.error('备用请求失败:', err);
          this.setData({
            car: null,
            loading: false
          });
          
          wx.showToast({
            title: '网络错误，请稍后重试',
            icon: 'none'
          });
        }
      });
    },
    
    // 重新加载
    reload() {
      if (this.data.carId) {
        this.loadCarDetail(this.data.carId);
      } else {
        wx.navigateBack();
      }
    },
    
    // 收藏车辆
    toggleFavorite() {
      this.setData({
        isFavorite: !this.data.isFavorite
      });
      wx.showToast({
        title: this.data.isFavorite ? '已收藏' : '已取消收藏',
        icon: 'success'
      });
    },
    
    // 分享车辆
    shareVehicle() {
      wx.showShareMenu({
        withShareTicket: true,
        menus: ['shareAppMessage', 'shareTimeline']
      });
    },
    
    // 联系客服
    contactService() {
      wx.showModal({
        title: '联系客服',
        content: '是否拨打客服电话？',
        success: (res) => {
          if (res.confirm) {
            wx.makePhoneCall({
              phoneNumber: '400-123-4567'
            });
          }
        }
      });
    },
    
    // 分享给好友
    onShareAppMessage() {
      if (!this.data.car) return {};
      
      return {
        title: `${this.data.car.makerName} ${this.data.car.brandName} - 每日仅需¥${this.data.car.rent}`,
        path: `/pages/car-detail/car-detail?id=${this.data.car.id}`,
        imageUrl: this.data.car.pic
      };
    }
  });